package com.wfc.libnetwork;

import android.util.TimeUtils;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

/***
 * 对OKHTTP的一个初始化
 */
public class ApiService {

    public static final  OkHttpClient okHttpClient;
    private static String sBaseUrl;
    public static Convert sConvert;

    static {
        HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
          okHttpClient=  new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .addInterceptor(interceptor)
                .build();
        //通过  TrustManager 来统一信任所有的证书
        TrustManager[] trustManagers=new TrustManager[]{
           new X509TrustManager() {
               @Override
               public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

               }

               @Override
               public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

               }

               @Override
               public X509Certificate[] getAcceptedIssuers() {
                   return new X509Certificate[0];
               }
           }
        };
        SSLContext ssl= null;
        try {
            ssl = SSLContext.getInstance("SSL");
            ssl.init(null,trustManagers,new SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(ssl.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                     //信任所有的域名
                    return true;
                }
            });

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }

   public  static  void init(String baseUrl,Convert convert){
        sBaseUrl=baseUrl;
        if(convert==null){
            convert=new JsonConvert();
        }
        sConvert=convert;

   }
}
